<template>
    <el-card class="main-card">
      <div class="title">{{!notice.id ? '公告发布' : '公告修改'}}</div>
      <div class="notice-title-container">
        <el-input v-model="notice.title" size="medium" placeholder="输入公告标题" />
        <el-button type="danger" size="medium" @click="openModel" style="margin-left: 10px"> 发布公告 </el-button>
      </div>
      <div class="notice-title-container">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="5"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :on-success="handleSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传5个文件</div>
        </el-upload>
      </div>
      <mavon-editor ref="md" v-model="notice.content" @imgAdd="uploadImg" style="height: calc(100vh - 260px)" />
      <el-dialog :visible.sync="addOrEdit" width="60%" top="3vh">
        <div class="dialog-title-container" slot="title">发布公告</div>
        <el-form label-width="100px" size="medium" :model="notice">
          <el-form-item label="公告类型">
            <el-select v-model="notice.noticeTypeId" placeholder="请选择公告类型">
              <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addOrEdit = false">取 消</el-button>
          <el-button type="danger" @click="saveOrUpdateNotice"> 发 表 </el-button>
        </div>
      </el-dialog>
    </el-card>
  </template>
  
  <script>
  import Cookies from 'js-cookie'
  import * as imageConversion from 'image-conversion'
  export default {
    activated() {
      const noticeId = this.$route.params.id
      console.log('noticeId' + noticeId)
      if (noticeId) {
        this.$http.get('/grant/noticeList/' + noticeId).then(({ data }) => {
          this.notice = data.data
          this.fileList = data.data.fileUrls.split(",").map((item, index) => ({
						url: item, // 图片 URL
						name: `img-${index}`, // 需要唯一 name
					}));
        })
      } else {
        const notice = sessionStorage.getItem('notice')
        if (notice) {
          this.notice = JSON.parse(notice)
        }
      }
    },
    data: function () {
      return {
        uploadUrl: window.SITE_CONFIG['apiURL'] + '/piclocal/upload/pic',
        headers: { token: Cookies.get('token') },
        fileList: [],
        addOrEdit: false,
        autoSave: true,
        typeList: [],
        notice: {
          id: null,
          noticeTypeId: '',
          title: '',
          content: '',
          fileUrls: ''
        }
      }
    },
    methods: {
      handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList;
      console.log(this.fileList);
      this.notice.fileUrls = this.fileList.map(f => f.url).join(',');
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.fileList.push(file);
      this.notice.fileUrls = this.fileList.map(f => f.response.data.imgAddress).join(',');
      console.log('111111:' + this.notice.fileUrls);
    },
      listCategories() {
        this.$http.get('/grant/noticeType/list').then(({ data }) => {
          this.typeList = data.data
        })
      },
      openModel() {
        if (this.notice.title.trim() == '') {
          this.$message.error('公告标题不能为空')
          return false
        }
        if (this.notice.content.trim() == '') {
          this.$message.error('公告内容不能为空')
          return false
        }
        this.listCategories()
        this.addOrEdit = true
      },
      handleAvatarSuccess(res, file) {
        console.log(res)
        console.log(file)
        this.notice.imgUrl = res.data.imgAddress;
      },
      beforeAvatarUpload(file) {
  
      },
      uploadImg(pos, $file) {
        var formdata = new FormData()
        formdata.append('file', $file)
        this.$http.post('/piclocal/upload/pic', formdata).then(({ data: res }) => {
          console.log('res.imgAddress:' + res.data.imgAddress)
          this.$refs.md.$img2Url(pos, res.data.imgAddress)
        })
      },
      saveOrUpdateNotice() {
        if (this.notice.title.trim() == '') {
          this.$message.error('公告标题不能为空')
          return false
        }
        if (this.notice.noticeTypeId.trim() == '') {
          this.$message.error('公告类型不能为空')
          return false
        }
        if (this.notice.content.trim() == '') {
          this.$message.error('公告内容不能为空')
          return false
        }
        this.$http[!this.notice.id ? "post" : "put"]('/grant/noticeList', this.notice).then(({ data: res }) => {
          if (res.code == 0) {
            this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name === 'notice-noticeList')
            this.$router.replace({ name: 'notice-noticeList' })
            this.$message({
              message: '创建成功',
              type: 'success'
            });
          } else {
            this.$message.error('创建失败');
          }
          this.addOrEdit = false
        })
        this.autoSave = false
      }
    }
  }
  </script>
  
  <style scoped>
  .notice-title-container {
    display: flex;
    align-items: center;
    margin-bottom: 1.25rem;
    margin-top: 2.25rem;
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  